﻿using System;

using BodaNetCommunications.Utilities.Results;
using BodaNetCommunications.Utilities.Tools;

namespace BodaNetCommunications.Commbase
{
    /// <summary>
    /// 所有数据转换类的静态辅助方法
    /// Static helper method for all data conversion classes
    /// </summary>
    public static class ByteTransformHelper
    {
        /// <summary>
        /// 结果转换操作的基础方法，需要支持类型，及转换的委托
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="result">源</param>
        /// <param name="translator">实际转换的委托</param>
        /// <returns>转换结果</returns>
        public static BodaResult<TResult> GetResultFromBytes<TResult>(BodaResult<byte[]> result, Func<byte[], TResult> translator)
        {
            try
            {
                if (result.Content == null)
                {
                    result.IsSuccess = false;
                    result.Message = $"GetResultFromBytes中的结果为空: {result.Message}";
                    return BodaResult.CreateFailedResult<TResult>(result);
                }

                if (result.IsSuccess)
                {
                    var transResult = translator(result.Content);
                    return BodaResult.CreateSuccessResult(transResult);
                }
                else
                {
                    return BodaResult.CreateFailedResult<TResult>(result);
                }
            }
            catch (Exception ex)
            {
                return new BodaResult<TResult>() { Message = StringResources.Language.DataTransformError + BodaBasicTool.ByteToHexString(result.Content) + $" : Length({result.Content.Length}) " + ex.Message };
            }
        }

        /// <summary>
        /// 结果转换操作的基础方法，需要支持类型，及转换的委托
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="result">源结果</param>
        /// <returns>转换结果</returns>
        public static BodaResult<TResult> GetResultFromArray<TResult>(BodaResult<TResult[]> result)
        {
            if (!result.IsSuccess) return BodaResult.CreateFailedResult<TResult>(result);
            try
            {
                var res = BodaResult.CreateSuccessResult(result.Content[0]);
                return res;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                return BodaResult.CreateFailedResult<TResult>(result);
            }
        }
    }
}